//
//  HUDToast.m
//  storeapp
//
//  Created by huangyi on 13-3-12.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "HudToast.h"

@interface HudToast ()

@end

@implementation HudToast

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

+(HudToast*)hudWithText:(NSString*)text{
    return [HudToast hudWithText:text timeout:3.0];
}
+(HudToast*)hudWithText:(NSString *)text timeout:(NSTimeInterval)timeout{
    HudToast *hud=[[HudToast alloc] init];
    hud.textString=text;
    hud.timeout=timeout;
    return hud;
}

-(void)buildHud{
    CGFloat width=120;
    CGFloat spacing=10;
    CGFloat radius=6;
    UIFont *font=UIFontFromString(@"@16");

    UIView *container=[[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:container];
    self.container=container;
    container.clipsToBounds=YES;
    container.backgroundColor=[UIColor colorWithWhite:0.9 alpha:1];
    container.layer.cornerRadius=radius;
    container.layer.shadowRadius=3;
    container.layer.shadowOpacity=1;
    container.layer.shadowOffset=CGSizeZero;
    container.layer.shadowColor=[UIColor blackColor].CGColor;
    container.autoresizingMask=(UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin);

    UILabel *textView=[[UILabel alloc] initWithFrame:CGRectZero];
    [container addSubview:textView];
    if (self.textString) {
        textView.text=self.textString;
        textView.font=font;
        textView.numberOfLines=0;
        textView.backgroundColor=[UIColor clearColor];
        [textView sizeToFit];
    }
    width=MAX(width, CGRectGetWidth(textView.frame));

    width=spacing+width+spacing;
    textView.frame=CGRectOffset(textView.frame, 0, spacing);
    textView.center=CGPointMake(width/2, textView.center.y);
    container.frame=CGRectMake(0, 0, width, CGRectGetMaxY(textView.frame)+spacing);
    container.center=CGPointMake(CGRectGetWidth(self.view.frame)/2, CGRectGetHeight(self.view.frame)/2);

    [self countdown];
}

-(void)countdown{
    double delayInSeconds = self.timeout;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self hide];
    });
}
-(void)show{
    [super show];
}
-(void)hide{
    [super hide];
}
@end
